import { ElLoading, ElMessage } from "element-plus";

export async function requestedMessage(callback, param = {}) {
    let options = {
        showSuccess: true,
        fullscreenLoading: true,
        errorHandle: undefined,
        finalHandle: undefined,
        ...param,
    };

    const loading =
        options.fullscreenLoading &&
        ElLoading.service({
            lock: true,
            text: "加载中",
            background: "rgba(0, 0, 0, 0.7)",
        });
    try {
        const msg = await callback();
        options.showSuccess &&
            ElMessage({
                grouping: true,
                message: msg,
                type: "success",
            });
    } catch (error) {
        if (error?.name === "CanceledError") {
            return;
        }
        options.errorHandle && options.errorHandle.call(this, error);
        if (typeof error === "string") {
            ElMessage({
                grouping: true,
                message: error,
                type: "error",
            });
        } else {
            ElMessage({
                grouping: true,
                message: "请求出错",
                type: "error",
            });
        }
    } finally {
        loading && loading?.close();
        options.finalHandle && options.finalHandle();
    }
}
